package com.dyl.auth.controller;

import com.dyl.auth.form.LoginBody;
import com.dyl.auth.form.LoginCodeVo;
import com.dyl.auth.service.SysLoginService;
import com.dyl.common.core.RR;
import com.dyl.common.core.domain.R;
import com.dyl.common.core.utils.XudenStringUtils;
import com.dyl.common.security.service.TokenService;
import com.dyl.system.api.model.LoginUser;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**功能描述：token 控制
 * @Auther:邓宇凌
 * @Date:2023/9/25
 * @Description:com.dyl.auth.controller
 * @version:1.0
 */
@RestController
public class TokenController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody form){
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo),"登录成功");
    }

    //1.2手机号验证码登录/获取登录凭证
    @ApiOperation(value = "用户登录(手机号/验证码)")
    @PostMapping("/sendLoginCode")
    public R loginCodeVo(@RequestBody LoginCodeVo loginCodeVo) {
        LoginUser userInfo = sysLoginService.loginCodeVo(loginCodeVo);
        return R.ok(tokenService.createToken(userInfo),"登录成功");
    }

    //获取验证码读秒
    @ApiOperation(value = "获取验证码读秒")
    @PostMapping("/sendSmsPhones")
    public RR loginGetCode(@RequestParam(value = "codeuuid")String codeUuid) {
        Long codeTime =  redisTemplate.opsForValue().getOperations().getExpire(codeUuid);
        if(codeTime==-2){
            return RR.ok().code(-2);
        }
        return RR.ok().code(200).data("codeTime",codeTime);
    }

    //发送验证码
    @ApiOperation(value = "发送验证码")
    @PostMapping("/sendSmsPhone")
    public RR sendSmsPhone(@RequestParam(value = "phone")String phone) {
        return sysLoginService.sendSmsPhone(phone);
    }

    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request){
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (XudenStringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

}
